import type { Fetcher } from 'swr'
import { del, get, patch, post, put } from './base'
import type { ApiKeysListResponse, AppDailyConversationsResponse, AppDailyEndUsersResponse, AppDailyMessagesResponse, AppDetailResponse, AppListResponse, AppSSOResponse, AppStatisticsResponse, AppTemplatesResponse, AppTokenCostsResponse, AppVoicesListResponse, CreateApiKeyResponse, GenerationIntroductionResponse, TracingConfig, TracingStatus, UpdateAppModelConfigResponse, UpdateAppSiteCodeResponse, UpdateOpenAIKeyResponse, ValidateOpenAIKeyResponse, WorkflowDailyConversationsResponse } from '@/models/app'
import type { CommonResponse } from '@/models/common'
import type { AppIconType, AppMode, ModelConfig } from '@/services/types/app'
// import type { TracingProvider } from '@/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type'

export const fetchAppList: Fetcher<AppListResponse, { url: string; params?: Record<string, any> }> = ({ url, params }) => {
  return get<AppListResponse>(url, { params })
}

export const fetchAppDetail = async ({ url, id }: { url: string; id: string }) => {
  //

  return {}
  return {
    "id": "9e208067-284b-49aa-9594-d5cb443d4fbb",
    "name": "Agent",
    "description": "",
    "mode": "agent-chat",
    "icon_type": "emoji",
    "icon": "\ud83e\udd16",
    "icon_background": "#FFEAD5",
    "icon_url": null,
    "enable_site": true,
    "enable_api": true,
    "model_config": {
      "opening_statement": "",
      "suggested_questions": [],
      "suggested_questions_after_answer": {
        "enabled": false
      },
      "speech_to_text": {
        "enabled": false
      },
      "text_to_speech": {
        "enabled": false,
        "voice": "",
        "language": ""
      },
      "retriever_resource": {
        "enabled": true
      },
      "annotation_reply": {
        "id": "754ad725-e1d3-47b6-a46c-969f9c28a998",
        "enabled": true,
        "score_threshold": 0.9,
        "embedding_model": {
          "embedding_provider_name": "openai",
          "embedding_model_name": "text-embedding-3-large"
        }
      },
      "more_like_this": {
        "enabled": false
      },
      "sensitive_word_avoidance": {
        "enabled": false,
        "type": "",
        "configs": []
      },
      "external_data_tools": [],
      "model": {
        "provider": "openai",
        "name": "gpt-4o-mini",
        "mode": "chat",
        "completion_params": {
          "stop": []
        }
      },
      "user_input_form": [
        {
          "text-input": {
            "label": "\u59d3\u540d",
            "variable": "a",
            "required": true,
            "max_length": 48,
            "default": ""
          }
        }
      ],
      "dataset_query_variable": "",
      "pre_prompt": "``` xml\n<instruction>\n\u8bf7\u6839\u636e\u4ee5\u4e0b\u6b65\u9aa4\u5b8c\u6210\u4efb\u52a1\uff1a\n1. \u56f4\u7ed5\u6982\u8981\u7684\u8f6f\u4ef6\u9700\u6c42\u8fdb\u884c\u7ec6\u5316\u76f8\u5173\u5185\u5bb9\uff0c\u4fdd\u8bc1\u903b\u8f91\u5b8c\u6574\u3002\n2. \u6839\u636e\u7ec6\u5316\u540e\u7684\u8f6f\u4ef6\u9700\u6c42\u4ece\u4e2d\u63d0\u53d6\u6240\u6709\u6d89\u53ca\u7684\u5bf9\u8c61\u3002\n3. \u5bf9\u6bcf\u4e2a\u5bf9\u8c61\u8fdb\u884c\u5206\u6790\uff0c\u5217\u51fa\u5176\u6240\u6709\u5c5e\u6027\u3002\n4. \u5bf9\u6bcf\u4e2a\u5bf9\u8c61\u8fdb\u884c\u5206\u6790\uff0c\u5217\u51fa\u5bf9\u8c61\u4e4b\u95f4\u7684\u5173\u7cfb\u3002\n5. \u786e\u4fdd\u8f93\u51fa\u4e0d\u5305\u542b\u4efb\u4f55XML\u6807\u7b7e\u3002\n</instruction>\n\n<example>\n\u8f6f\u4ef6\u9700\u6c42\u63cf\u8ff0\uff1a\u7528\u6237\u53ef\u4ee5\u6ce8\u518c\u8d26\u6237\uff0c\u767b\u5f55\u540e\u67e5\u770b\u4e2a\u4eba\u4fe1\u606f\u548c\u8ba2\u5355\u5386\u53f2\u3002\n\u5206\u6790\u7ed3\u679c\uff1a\n\u5bf9\u8c61\uff1a\u7528\u6237\n\u5c5e\u6027\uff1a\u7528\u6237ID\u3001\u7528\u6237\u540d\u79f0\u3001\u7528\u6237\u5bc6\u7801\n\u5173\u7cfb\uff1a\u7528\u6237\u4fe1\u606f\u4e00\u5bf9\u4e00\u5173\u7cfb\u3001\u4e0e\u767b\u5f55\u65e5\u5fd7\u4e00\u5bf9\u591a\u5173\u7cfb\u3001\u4e0e\u8ba2\u5355\u4e00\u5bf9\u591a\u5173\u7cfb\n\n\u5bf9\u8c61\uff1a\u7528\u6237\u4fe1\u606f\n\u5c5e\u6027\uff1a\u7528\u6237ID\u3001\u624b\u673a\u53f7\u3001\u90ae\u7bb1\u3001\u5730\u5740\n\u5173\u7cfb\uff1a\u7528\u6237\u4fe1\u606f\u4e00\u5bf9\u4e00\u5173\u7cfb\u3001\u4e0e\u767b\u5f55\u65e5\u5fd7\u4e00\u5bf9\u591a\u5173\u7cfb\u3001\u4e0e\u8ba2\u5355\u4e00\u5bf9\u591a\u5173\u7cfb\n\n\u5bf9\u8c61\uff1a\u767b\u5f55\u65e5\u5fd7\n\u5c5e\u6027\uff1a\u7528\u6237ID\u3001\u767b\u5f55\u65f6\u95f4\u3001\u767b\u5f55IP\n\n\u5bf9\u8c61\uff1a\u5546\u54c1\n\u5c5e\u6027\uff1a\u5546\u54c1ID\u3001\u5546\u54c1\u540d\u79f0\u3001\u91d1\u989d\u3001\u5546\u54c1\u4fe1\u606f\n\n\u5bf9\u8c61\uff1a\u8ba2\u5355\n\u5c5e\u6027\uff1a\u8ba2\u5355ID\u3001\u7528\u6237ID\u3001\u8ba2\u5355SN\u3001\u5546\u54c1ID\u3001\u91d1\u989d\u3001\u652f\u4ed8\u72b6\u6001\u3001\u5730\u5740\u4fe1\u606f\n\n......\n</example>\n```",
      "agent_mode": {
        "max_iteration": 5,
        "enabled": true,
        "strategy": "function_call",
        "tools": [
          {
            "provider_id": "chart",
            "provider_type": "builtin",
            "provider_name": "chart",
            "tool_name": "bar_chart",
            "tool_label": "\u67f1\u72b6\u56fe",
            "tool_parameters": {
              "data": "",
              "x_axis": ""
            },
            "enabled": true
          },
          {
            "provider_id": "duckduckgo",
            "provider_type": "builtin",
            "provider_name": "duckduckgo",
            "tool_name": "ddgo_ai",
            "tool_label": "DuckDuckGo AI\u804a\u5929",
            "tool_parameters": {
              "query": "",
              "model": ""
            },
            "enabled": true
          }
        ],
        "prompt": null
      },
      "prompt_type": "simple",
      "chat_prompt_config": {},
      "completion_prompt_config": {},
      "dataset_configs": {
        "retrieval_model": "multiple",
        "top_k": 4,
        "reranking_enable": true,
        "datasets": {
          "datasets": []
        }
      },
      "file_upload": {
        "image": {
          "detail": "high",
          "enabled": false,
          "number_limits": 3,
          "transfer_methods": [
            "remote_url",
            "local_file"
          ]
        },
        "enabled": false,
        "allowed_file_types": [],
        "allowed_file_extensions": [
          ".JPG",
          ".JPEG",
          ".PNG",
          ".GIF",
          ".WEBP",
          ".SVG",
          ".MP4",
          ".MOV",
          ".MPEG",
          ".MPGA"
        ],
        "allowed_file_upload_methods": [
          "remote_url",
          "local_file"
        ],
        "number_limits": 3
      },
      "created_by": "2099825c-856e-4ce8-b035-05df64e53470",
      "created_at": 1735882049,
      "updated_by": "2099825c-856e-4ce8-b035-05df64e53470",
      "updated_at": 1735882049
    },
    "workflow": null,
    "site": {
      "access_token": "9ODan2oQLqNkpahH",
      "code": "9ODan2oQLqNkpahH",
      "title": "Agent",
      "icon_type": "emoji",
      "icon": "\ud83e\udd16",
      "icon_background": "#FFEAD5",
      "icon_url": null,
      "description": null,
      "default_language": "en-US",
      "chat_color_theme": null,
      "chat_color_theme_inverted": false,
      "customize_domain": null,
      "copyright": null,
      "privacy_policy": null,
      "custom_disclaimer": "",
      "customize_token_strategy": "not_allow",
      "prompt_public": false,
      "app_base_url": "http://localhost",
      "show_workflow_steps": true,
      "use_icon_as_answer_icon": false,
      "created_by": "2099825c-856e-4ce8-b035-05df64e53470",
      "created_at": 1735865665,
      "updated_by": "2099825c-856e-4ce8-b035-05df64e53470",
      "updated_at": 1735865665
    },
    "api_base_url": "http://localhost/v1",
    "use_icon_as_answer_icon": true,
    "created_by": "2099825c-856e-4ce8-b035-05df64e53470",
    "created_at": 1735865665,
    "updated_by": "2099825c-856e-4ce8-b035-05df64e53470",
    "updated_at": 1736065449,
    "deleted_tools": []
  };
}

export const fetchAppSSO = async ({ appId }: { appId: string }) => {
  return get<AppSSOResponse>(`/enterprise/app-setting/sso?appID=${appId}`)
}
export const updateAppSSO = async ({ id, enabled }: { id: string; enabled: boolean }) => {
  return post('/enterprise/app-setting/sso', { body: { app_id: id, enabled } })
}

export const fetchAppTemplates: Fetcher<AppTemplatesResponse, { url: string }> = ({ url }) => {
  return get<AppTemplatesResponse>(url)
}

export const createApp: Fetcher<AppDetailResponse, { name: string; icon_type?: AppIconType; icon?: string; icon_background?: string; mode: AppMode; description?: string; config?: ModelConfig }> = ({ name, icon_type, icon, icon_background, mode, description, config }) => {
  return post<AppDetailResponse>('apps', { body: { name, icon_type, icon, icon_background, mode, description, model_config: config } })
}

export const updateAppInfo: Fetcher<AppDetailResponse, { appID: string; name: string; icon_type: AppIconType; icon: string; icon_background?: string; description: string; use_icon_as_answer_icon?: boolean }> = ({ appID, name, icon_type, icon, icon_background, description, use_icon_as_answer_icon }) => {
  return put<AppDetailResponse>(`apps/${appID}`, { body: { name, icon_type, icon, icon_background, description, use_icon_as_answer_icon } })
}

export const copyApp: Fetcher<AppDetailResponse, { appID: string; name: string; icon_type: AppIconType; icon: string; icon_background?: string | null; mode: AppMode; description?: string }> = ({ appID, name, icon_type, icon, icon_background, mode, description }) => {
  return post<AppDetailResponse>(`apps/${appID}/copy`, { body: { name, icon_type, icon, icon_background, mode, description } })
}

export const exportAppConfig: Fetcher<{ data: string }, { appID: string; include?: boolean }> = ({ appID, include = false }) => {
  return get<{ data: string }>(`apps/${appID}/export?include_secret=${include}`)
}

export const importApp: Fetcher<AppDetailResponse, { data: string; name?: string; description?: string; icon_type?: AppIconType; icon?: string; icon_background?: string }> = ({ data, name, description, icon_type, icon, icon_background }) => {
  return post<AppDetailResponse>('apps/import', { body: { data, name, description, icon_type, icon, icon_background } })
}

export const importAppFromUrl: Fetcher<AppDetailResponse, { url: string; name?: string; description?: string; icon?: string; icon_background?: string }> = ({ url, name, description, icon, icon_background }) => {
  return post<AppDetailResponse>('apps/import/url', { body: { url, name, description, icon, icon_background } })
}

export const switchApp: Fetcher<{ new_app_id: string }, { appID: string; name: string; icon_type: AppIconType; icon: string; icon_background?: string | null }> = ({ appID, name, icon_type, icon, icon_background }) => {
  return post<{ new_app_id: string }>(`apps/${appID}/convert-to-workflow`, { body: { name, icon_type, icon, icon_background } })
}

export const deleteApp: Fetcher<CommonResponse, string> = (appID) => {
  return del<CommonResponse>(`apps/${appID}`)
}

export const updateAppSiteStatus: Fetcher<AppDetailResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
  return post<AppDetailResponse>(url, { body })
}

export const updateAppApiStatus: Fetcher<AppDetailResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
  return post<AppDetailResponse>(url, { body })
}

// path: /apps/{appId}/rate-limit
export const updateAppRateLimit: Fetcher<AppDetailResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
  return post<AppDetailResponse>(url, { body })
}

export const updateAppSiteAccessToken: Fetcher<UpdateAppSiteCodeResponse, { url: string }> = ({ url }) => {
  return post<UpdateAppSiteCodeResponse>(url)
}

export const updateAppSiteConfig = ({ url, body }: { url: string; body: Record<string, any> }) => {
  return post<AppDetailResponse>(url, { body })
}

export const getAppDailyMessages: Fetcher<AppDailyMessagesResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<AppDailyMessagesResponse>(url, { params })
}

export const getAppDailyConversations: Fetcher<AppDailyConversationsResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<AppDailyConversationsResponse>(url, { params })
}

export const getWorkflowDailyConversations: Fetcher<WorkflowDailyConversationsResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<WorkflowDailyConversationsResponse>(url, { params })
}

export const getAppStatistics: Fetcher<AppStatisticsResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<AppStatisticsResponse>(url, { params })
}

export const getAppDailyEndUsers: Fetcher<AppDailyEndUsersResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<AppDailyEndUsersResponse>(url, { params })
}

export const getAppTokenCosts: Fetcher<AppTokenCostsResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<AppTokenCostsResponse>(url, { params })
}

export const updateAppModelConfig: Fetcher<UpdateAppModelConfigResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
  return post<UpdateAppModelConfigResponse>(url, { body })
}

// For temp testing
export const fetchAppListNoMock: Fetcher<AppListResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<AppListResponse>(url, params)
}

export const fetchApiKeysList: Fetcher<ApiKeysListResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return get<ApiKeysListResponse>(url, params)
}

export const delApikey: Fetcher<CommonResponse, { url: string; params: Record<string, any> }> = ({ url, params }) => {
  return del<CommonResponse>(url, params)
}

export const createApikey: Fetcher<CreateApiKeyResponse, { url: string; body: Record<string, any> }> = ({ url, body }) => {
  return post<CreateApiKeyResponse>(url, body)
}

export const validateOpenAIKey: Fetcher<ValidateOpenAIKeyResponse, { url: string; body: { token: string } }> = ({ url, body }) => {
  return post<ValidateOpenAIKeyResponse>(url, { body })
}

export const updateOpenAIKey: Fetcher<UpdateOpenAIKeyResponse, { url: string; body: { token: string } }> = ({ url, body }) => {
  return post<UpdateOpenAIKeyResponse>(url, { body })
}

export const generationIntroduction: Fetcher<GenerationIntroductionResponse, { url: string; body: { prompt_template: string } }> = ({ url, body }) => {
  return post<GenerationIntroductionResponse>(url, { body })
}

export const fetchAppVoices: Fetcher<AppVoicesListResponse, { appId: string; language?: string }> = ({ appId, language }) => {
  language = language || 'en-US'
  return get<AppVoicesListResponse>(`apps/${appId}/text-to-audio/voices?language=${language}`)
}

// Tracing
export const fetchTracingStatus: Fetcher<TracingStatus, { appId: string }> = ({ appId }) => {
  return get(`/apps/${appId}/trace`)
}

export const updateTracingStatus: Fetcher<CommonResponse, { appId: string; body: Record<string, any> }> = ({ appId, body }) => {
  return post(`/apps/${appId}/trace`, { body })
}

export const fetchTracingConfig: Fetcher<TracingConfig & { has_not_configured: true }, { appId: string; provider: TracingProvider }> = ({ appId, provider }) => {
  return get(`/apps/${appId}/trace-config`, {
    params: {
      tracing_provider: provider,
    },
  })
}

export const addTracingConfig: Fetcher<CommonResponse, { appId: string; body: TracingConfig }> = ({ appId, body }) => {
  return post(`/apps/${appId}/trace-config`, { body })
}

export const updateTracingConfig: Fetcher<CommonResponse, { appId: string; body: TracingConfig }> = ({ appId, body }) => {
  return patch(`/apps/${appId}/trace-config`, { body })
}

export const removeTracingConfig: Fetcher<CommonResponse, { appId: string; provider: TracingProvider }> = ({ appId, provider }) => {
  return del(`/apps/${appId}/trace-config?tracing_provider=${provider}`)
}

export const importDSL: Fetcher<any, { mode: any; yaml_content?: string; yaml_url?: string; app_id?: string; name?: string; description?: string; icon_type?: AppIconType; icon?: string; icon_background?: string }> = ({ mode, yaml_content, yaml_url, app_id, name, description, icon_type, icon, icon_background }) => {
}

export const importDSLConfirm: Fetcher<any, { import_id: string }> = ({ import_id }) => {
}